package com.oceansoft.mobile.econsole.weixin.controller;

import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory;
import com.oceansoft.mobile.econsole.modules.weixin.entity.WxMember;
import com.oceansoft.mobile.econsole.modules.weixin.service.IWxMemberService;
import com.oceansoft.mobile.econsole.weixin.api.MenuAPI;
import com.oceansoft.mobile.econsole.weixin.api.entity.Menu;
import com.oceansoft.mobile.econsole.weixin.api.entity.MenuButton;
import com.oceansoft.mobile.econsole.weixin.api.enums.MenuType;
import com.oceansoft.mobile.econsole.weixin.api.enums.ResultType;
import com.oceansoft.mobile.econsole.weixin.api.response.GetSignatureResponse;
import com.oceansoft.mobile.econsole.weixin.api.response.GetUserInfoResponse;
import com.oceansoft.mobile.econsole.weixin.message.BaseMsg;
import com.oceansoft.mobile.econsole.weixin.message.req.BaseEvent;
import com.oceansoft.mobile.econsole.weixin.servlet.WeixinControllerSupport;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory.HOST;
import static com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory.SYHOST;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 微信接口
 *
 * @author jin.xu
 * @version 2015-04-02
 */
@Controller
@RequestMapping("weixin")
public class WeixinController extends WeixinControllerSupport  {
    private static final Logger log = LoggerFactory.getLogger(WeixinController.class);
    @Resource
    private IWxMemberService wxMemberService;



    @ResponseBody
    @RequestMapping(value = "jssdk", method = GET)
    public GetSignatureResponse jsSdk(HttpServletRequest request) {
    	return WxFactory.buildJsAPI().getSignature(WxFactory.DLYC);
    }
    
    /*@ResponseBody
    @RequestMapping(value = "pop", method = GET)
    public GetSignatureResponse pop(HttpServletRequest request) {
        return WxFactory.buildJsAPI().getSignature(WxFactory.POP);
    }*/
    
    /**
     *  创建菜单
     */
    @ResponseBody
    @RequestMapping(value = "createmenu", method = GET)
    public String createMenu(HttpServletRequest request) {
    	MenuAPI menuAPI = WxFactory.buildMenuAPI();

        //先删除之前的菜单
        menuAPI.deleteMenu();
        Menu m_req = new Menu();
        
        //-------------------------------------------第一个主菜单
        MenuButton main1 = new MenuButton();
        main1.setType(MenuType.VIEW);
        main1.setKey("main1");
        main1.setName("微警务");

        //准备子菜单
        MenuButton sub1_1 = new MenuButton();
        sub1_1.setKey("sub1_1");
        sub1_1.setName("交通违章查询");
        sub1_1.setType(MenuType.VIEW);
        sub1_1.setUrl(SYHOST + "/weixinquery/gotoJdcwfCx");
        
        MenuButton sub1_2 = new MenuButton();
        sub1_2.setKey("sub1_2");
        sub1_2.setName("驾驶证记分查询");
        sub1_2.setType(MenuType.VIEW);
        sub1_2.setUrl(SYHOST + "/weixinquery/gotoJszjfCx");
        
        MenuButton sub1_3 = new MenuButton();
        sub1_3.setKey("sub1_3");
        sub1_3.setName("重名查询");
        sub1_3.setType(MenuType.VIEW);
        sub1_3.setUrl(SYHOST + "/weixinquery/gotoCmCx?type=C");
        
        MenuButton sub1_4 = new MenuButton();
        sub1_4.setKey("sub1_4");
        sub1_4.setName("线索举报");
        sub1_4.setType(MenuType.VIEW);
        sub1_4.setUrl(SYHOST + "/weixinquery/wxjbxsjbym?pt=W");
        
        MenuButton sub1_5 = new MenuButton();
        sub1_5.setKey("sub1_5");
        sub1_5.setName("更多服务");
        sub1_5.setType(MenuType.VIEW);
        sub1_5.setUrl(HOST+ "/wx_member/oauth?t=" + Math.abs(new Random().nextInt()));

        List<MenuButton> list1 = new ArrayList<>();
        list1.add(sub1_1);
        list1.add(sub1_2);
        list1.add(sub1_3);
        list1.add(sub1_4);
        list1.add(sub1_5);
        main1.setSubButton(list1);
        
      //-------------------------------------------第二个主菜单
        MenuButton main2 = new MenuButton();
        main2.setType(MenuType.VIEW);
        main2.setKey("main2");
        main2.setName("办事大厅");
        main2.setUrl(SYHOST+ "/api/case/baseOauth?t=" + Math.abs(new Random().nextInt()));
        //准备子菜单
        /*MenuButton sub2_1 = new MenuButton();
        sub2_1.setKey("sub2_1");
        sub2_1.setName("本地户口申报");
        sub2_1.setType(MenuType.VIEW);
        sub2_1.setUrl(HOST + "/bszn");

        MenuButton sub2_2 = new MenuButton();
        sub2_2.setKey("sub2_2");
        sub2_2.setName("交通违法查询");
        sub2_2.setType(MenuType.VIEW);
        sub2_2.setUrl(HOST + "/matter/wzcx");

        MenuButton sub2_3 = new MenuButton();
        sub2_3.setKey("sub2_3");
        sub2_3.setName("身份证办理进度");
        sub2_3.setType(MenuType.VIEW);
        sub2_3.setUrl(HOST + "/matter/identity_card");
        
        MenuButton sub2_3 = new MenuButton();
        sub2_3.setKey("sub2_3");
        sub2_3.setName("人口信息申报");
        sub2_3.setType(MenuType.VIEW);
        sub2_3.setUrl("http://10.35.0.43:18080");
        sub2_3.setUrl(HOST + "/report/index");

        MenuButton sub2_4 = new MenuButton();
        sub2_4.setKey("sub2_4");
        sub2_4.setName("路况查询");
        sub2_4.setType(MenuType.VIEW);
        sub2_4.setUrl(HOST + "/bmsrv/lkcx");
        sub2_4.setUrl(HOST + "/bmsrv/lkcx/oauth?t=" + Math.abs(new Random().nextInt()));
        
        List<MenuButton> list2 = new ArrayList<MenuButton>();
        list2.add(sub2_1);
        list2.add(sub2_2);
        list2.add(sub2_3);
        list2.add(sub2_4);
        main2.setSubButton(list2);*/

      //-------------------------------------------第二个主菜单
        MenuButton main3 = new MenuButton();
        main3.setType(MenuType.VIEW);
        main3.setKey("main3");
        main3.setName("个人中心");
        main3.setUrl(HOST+ "/percenter/oauth?t=" + Math.abs(new Random().nextInt()));

//        MenuButton main3 = new MenuButton();
//        main3.setType(MenuType.VIEW);
//        main3.setKey("main3");
//        main3.setName("微信矩阵");
//        main3.setUrl("http://gawx.daqing.gov.cn/econsole"
//                + "/api/police/wechatAccounts?title=&areaId=&type=1&pageindex=1&t=" + Math.abs(new Random().nextInt()));
/*
        MenuButton sub3_1 = new MenuButton();
        sub3_1.setKey("sub3_1");
        sub3_1.setName("微信矩阵");
        sub3_1.setType(MenuType.VIEW);
        sub3_1.setUrl("http://gabsdt.daqing.gov.cn/econsole"
                + "/api/police/wechatAccounts?title=&areaId=&type=1&pageindex=1&t=" + Math.abs(new Random().nextInt()));

        MenuButton sub3_2 = new MenuButton();
        sub3_2.setKey("sub3_2");
        sub3_2.setName("微博矩阵");
        sub3_2.setType(MenuType.VIEW);
        sub3_2.setUrl("http://gabsdt.daqing.gov.cn/econsole"
                + "/api/police/wechatAccounts?title=&areaId=&type=2&pageindex=1&t=" + Math.abs(new Random().nextInt()));
*/

/*        List<MenuButton> list3 = new ArrayList<MenuButton>();
        list3.add(sub3_1);
        list3.add(sub3_2);
        main3.setSubButton(list3);*/

        //准备子菜单
        /*MenuButton sub3_1 = new MenuButton();
        sub3_1.setKey("sub3_1");
        sub3_1.setName("我的办件");
        sub3_1.setType(MenuType.VIEW);
        sub3_1.setUrl("");

        MenuButton sub3_2 = new MenuButton();
        sub3_2.setKey("sub3_2");
        sub3_2.setName("信息绑定");
        sub3_2.setType(MenuType.VIEW);
        sub3_2.setUrl(HOST + "/member/info_bind");

        MenuButton sub3_3 = new MenuButton();
        sub3_3.setKey("sub3_3");
        sub3_3.setName("建议意见");
        sub3_3.setType(MenuType.VIEW);
        sub3_3.setUrl(HOST + "/member/tsjy");

        List<MenuButton> list3 = new ArrayList<MenuButton>();
        list3.add(sub3_1);
        list3.add(sub3_2);
        list3.add(sub3_3);
        main3.setSubButton(list3);*/
        
        List<MenuButton> mainList = new ArrayList<MenuButton>();
        mainList.add(main1);
        mainList.add(main2);
        mainList.add(main3);

        //将主菜单加入请求对象
        m_req.setButton(mainList);
        log.debug(m_req.toJsonString());
        //创建菜单
        ResultType resultType = menuAPI.createMenu(m_req);
        log.debug(resultType.toString());
        
        return "build success";
    }
    
    /**
     * 重写关注事件处理
     */
    @Override
    protected BaseMsg handleSubscribe(BaseEvent event){
    	GetUserInfoResponse user = WxFactory.buildUserAPI().getUserInfo(event.getFromUserName());
        WxMember member = new WxMember();
    	try {

    		if(CollectionUtils.isEmpty(wxMemberService.loadWxMemberByOpenId(user.getOpenid()))){
                BeanUtils.copyProperties(member, user);
    			member.setId(UUID.randomUUID().toString());
                member.setOpenId(user.getOpenid());
    			member.setHeadimgUrl(user.getHeadimgurl());
                member.setWxOpenId(event.getToUserName());
                member.setCreateTime(new Date());
    			wxMemberService.saveWxMember(member);
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return super.handleSubscribe(event);
    }

    @Override
    protected BaseMsg handleUnsubscribe(BaseEvent event) {
    	GetUserInfoResponse user = WxFactory.buildUserAPI().getUserInfo(event.getFromUserName());
    	try {
    		wxMemberService.delWxMemberByOpenId(user.getOpenid());
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return super.handleUnsubscribe(event);
    }

	@Override
	protected String getToken() {
		return WxFactory.TOKEN;
	}

	@Override
	protected String getAppId() {
		return WxFactory.APPID;
	}

	@Override
	protected String getAESKey() {
		return WxFactory.AESKEY;
	}

	@Override
	protected String getAppSecret() {
		return WxFactory.APPSECRET;
	}

    @ResponseBody
    @RequestMapping(value = "version", method = GET)
    public Result getVersion () {
        return new Result(Result.SUCC,"1.0");
    }

}